﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        private Socket client;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //1.创建服务端，使用IPV4， 字节流，TCP协议
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2.绑定本机IP和8888号端口
            server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

            //3.监听客户端，最多监听十个
            server.Listen(10);

            //4.阻塞等待客户端的连接
            client = server.Accept();

            //5.阻塞等待接收客户端消息
            byte[] buffer = new byte[1024];
            int v = client.Receive(buffer);
            label1.Text = Encoding.UTF8.GetString(buffer, 0, v);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //1.向客户端发送消息
            client.Send(Encoding.UTF8.GetBytes(textBox1.Text));

            //5.阻塞等待接收客户端消息
            byte[] buffer = new byte[1024];
            int v = client.Receive(buffer);
            label1.Text = Encoding.UTF8.GetString(buffer, 0, v);
        }
    }
}
